<template>
  <el-form
    ref="FormRef"
    :model="form"
    :rules="rules"
    label-position="top"
    require-asterisk-position="right"
    v-loading="loading"
  >
    <el-form-item label="知识库名称" prop="name">
      <el-input
        v-model="form.name"
        placeholder="请输入知识库名称"
        maxlength="30"
        show-word-limit
        @blur="form.name = form.name.trim()"
      />
    </el-form-item>
    <el-form-item
      label="知识库描述"
      prop="desc"
    >
      <el-input
        v-model="form.desc"
        type="textarea"
        placeholder="描述知识库的内容，详尽的描述将帮助AI能深入理解该知识库的内容，能更准确的检索到内容，提高该知识库的命中率。"
        maxlength="100"
        show-word-limit
        :autosize="{ minRows: 3 }"
        @blur="form.desc = form.desc?.trim()"
      />
    </el-form-item>
    <!-- <el-form-item
      label="向量模型"
      prop="embedding_mode_id"
    >
      <ModelSelect
        v-model="form.embedding_mode_id"
        placeholder="请选择向量模型"
        :options="modelOptions"
      ></ModelSelect>
    </el-form-item> -->
  </el-form>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
// import { groupBy } from 'lodash'
// import useStore from '@/stores'
import type { datasetData } from '@/api/type/dataset'
import { check } from '@/servers/ai/api/zhishiku'

const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  }
})
// const { model } = useStore()
const form = ref<datasetData>({
  name: '',
  desc: '',
  // embedding_mode_id: ''
})

const oldRow: any = ref(null)


/** 知识库名称校验 */
const validateNameDuplicate = async (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('知识库名称不能为空'));
    return;
  }
  if (value.trim().length > 30) {
    callback(new Error('知识库名称长度不能大于30个字符'));
    return;
  }

  const specialChars = /[*?"<>]/;
  if (specialChars.test(value)) {
    callback(new Error('知识库名不能包含特殊符号：*？"<>'));
    return;
  }

  // 编辑时候新旧值相等
  if(oldRow.value?.name === value) {
    return callback();
  }

  try {
    const res = await check({ name: value });
    if (res.data.data) {
      callback();
    } else {
      callback(new Error('知识库名称重复，请重新输入'));
    }
  } catch (error: any) {
    if (error.response.data.msg.indexOf('当前已存在该名称') !== -1) {
      callback(new Error('知识库名称重复，请重新输入'));
    } else {
      callback(new Error('知识库名不能包含特殊符号：*？"<>'));
    }
  }
};


const rules = reactive({
  name: [
    { required: true, validator: validateNameDuplicate, trigger: 'blur' },
  ],
  desc: [
    {
      required: true,
      message: '请输入知识库描述',
      trigger: 'blur'
    }
  ],
  // embedding_mode_id: [
  //   {
  //     required: true,
  //     message: '请选择向量模型',
  //     trigger: 'change'
  //   }
  // ]
})

const FormRef = ref()
const loading = ref(false)
// const modelOptions = ref<any>([])

watch(
  () => form.value,
  (value) => {
    if (value?.name && !oldRow.value?.name) {
      oldRow.value = {
        name: value.name
      }; // 存储初始值
    }
  },
  {
    immediate: true
  }
);

watch(
  () => props.data,
  (value) => {
    if (value && JSON.stringify(value) !== '{}') {
      form.value.name = value.name
      form.value.desc = value.desc
      // form.value.embedding_mode_id = value.embedding_mode_id
    }
  },
  {
    immediate: true
  }
)
/*
  表单校验
*/
function validate() {
  if (!FormRef.value) return
  return FormRef.value.validate((valid: any) => {
    return valid
  })
}

// function getModel() {
//   loading.value = true
//   model
//     .asyncGetModel({ model_type: 'EMBEDDING' })
//     .then((res: any) => {
//       modelOptions.value = groupBy(res?.data, 'provider')
//       loading.value = false
//     })
//     .catch(() => {
//       loading.value = false
//     })
// }

onMounted(() => {
  // getModel()
})
onUnmounted(() => {
  form.value = {
    name: '',
    desc: '',
    // embedding_mode_id: ''
  }
  FormRef.value?.clearValidate()
  oldRow.value = null
})

defineExpose({
  validate,
  form
})
</script>
<style scoped lang="scss"></style>
